package server

import (
	"github.com/gin-gonic/gin"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/http"
	"transfer-service/internal/conf"
	"transfer-service/internal/service"
	transfer "transfer/api/transfer_srv"
	"transfer/pkg/encoder"
)

// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Bootstrap,
	wsService *service.WebsocketService,
	logger log.Logger) *http.Server {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			logging.Server(logger),
		),
	}
	config := c.GetServer()
	if config.Http.Network != "" {
		opts = append(opts, http.Network(config.Http.Network))
	}
	if config.Http.Addr != "" {
		opts = append(opts, http.Address(config.Http.Addr))
	}
	if config.Http.Timeout != nil {
		opts = append(opts, http.Timeout(config.Http.Timeout.AsDuration()))
	}
	// 增加成功自定义json返回值
	opts = append(opts, http.ResponseEncoder(encoder.ResponseEncoder))
	// 增加错误自定义json返回值
	opts = append(opts, http.ErrorEncoder(encoder.ErrorEncoder))
	srv := http.NewServer(opts...)
	// warn do not move
	router := gin.Default()
	srv.HandlePrefix("/", router)
	transfer.RegisterWebsocketGinServer(router, wsService)
	return srv
}
